import qs from 'qs';
import util from '@/libs/util';


util.ajax.defaults.headers.common = {
  'X-Requested-With': 'XMLHttpRequest'
};


util.ajax.interceptors.request.use((config) => {
  const isLoading = config.isLoading || config.isLoading === undefined
  if (isLoading) {
    // 开启loading
    util.openLoading();
  }

  // 获取token
  const token = util.wsCache.get(`crmToken`);
  config.headers.common.Authorization = `Bearer ${token}`;
  return config;
}, error => Promise.reject(error));

util.ajax.interceptors.response.use((response) => {
  // 如果后端有新的token则重新缓存
  const newToken = response.headers['new-token'];
  if (newToken) {
    util.wsCache.set(`crmToken`, newToken);
  }

  // 关闭loading
  util.closeLoading();
  return response;

}, (error) => {
  const res = error.response
  const { catchCodes = [], catchErrors = [] } = res.config.params ? res.config.params : res.config
  let { code, error_code } = res ? res.data : {}
  if (!code) {
    code = res.status;
  }
  // 不需要捕捉的code就自动默认处理
  if (catchCodes.indexOf(code) === -1) {
    switch (code) {
      case 401:
        // 前往登录
        util.error('登录信息已过期，请重新登录！');
        setTimeout(() => {
          window.location.href = '/login';
        }, 1000)
        break;

      case 404:
        util.error('查询信息不存在');
        break;

      case 406:
        // 不捕捉的话就直接默认提示
        if (catchErrors.indexOf(error_code) === -1) {
          util.error(res.data.message);
        }
        break;

      case 409:
        util.error('参数错误');
        break;

      case 422:
        if (res.data.errors) {
          let arr = [];
          for (const key in res.data.errors) {
            res.data.errors[key].forEach((item) => {
              arr.push(item);
            });
          }
          const errors = arr.length > 0 ? arr.join("\n") : arr;
          util.error(errors);
        } else {
          util.error(res.data.message);
        }
        break;

      case 500:
        util.error(res.data.message || '服务器开了一会小差~');
        break;

      default:
        util.error(res.data.message);
    }
  }

  // 关闭loading
  util.closeLoading();
  return Promise.reject(res);
});

export default {
  post(url, params = {}) {
    const {isLoading = true, catchCodes = [], catchErrors = []} = params;
    return util.ajax.request({
      method: 'post',
      url,
      data: qs.stringify(params),
      timeout: 30000,
      isLoading,
      catchCodes,
      catchErrors,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
    });
  },


  get(url, params = {}) {
    const {isLoading = true, catchCodes = [], catchErrors = []} = params;
    return util.ajax.request({
      method: 'get',
      url,
      params,
      paramsSerializer: query => qs.stringify(query),
      isLoading,
      catchCodes,
      catchErrors
    });
  },

  delete(url, params = {}) {
    const {isLoading = true, catchCodes = [], catchErrors = []} = params;
    return util.ajax.request({
      method: 'delete',
      url,
      params,
      isLoading,
      catchCodes,
      catchErrors
    });
  },

  put(url, params = {}) {
    const {isLoading = true, catchCodes = [], catchErrors = []} = params;
    return util.ajax.request({
      method: 'put',
      url,
      data: qs.stringify(params),
      isLoading,
      catchCodes,
      catchErrors,
      timeout: 30000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
    });
  },
};
